//
//  LoginViewController.swift
//  puretennis
//
//  Created by IYE Technologies on 11/12/14.
//  Copyright (c) 2014 IYE Technologies. All rights reserved.
//

import UIKit
class LoginViewController: UIViewController,TencentLoginDelegate,TencentSessionDelegate {

    var notReachableView:UIView?;

    @IBOutlet weak var accountLoginButton: UIButton!
    @IBOutlet weak var tencentLoginButtion: UIButton!
    
    @IBOutlet weak var hideInputBoxButton:UIButton!;
    @IBOutlet weak var usernameTextField: CustomTextField!
    @IBOutlet weak var passwordTextField: CustomTextField!
     @IBOutlet weak var loginButton: UIButton!
    
    var tencentOAuth:TencentOAuth!;
    var permissions = [kOPEN_PERMISSION_GET_INFO,kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,"add_t"];
    var userInfo:UserInfo!;
    var adjustContentToAccommodateKeyboard:AdjustContentToAccommodateKeyboard!;
    
    override func viewDidLoad() {
        super.viewDidLoad();
        var backgroundImageView = UIImageView(image: UIImage(named: "login_bg"));
        backgroundImageView.frame = UIScreen.mainScreen().bounds;
        self.view.insertSubview(backgroundImageView, atIndex: 0);
        UIApplication.sharedApplication().statusBarHidden = true;
        self.tencentOAuth = TencentOAuth(appId: Properties.TENCENT_APPID, andDelegate: self);
        self.checkTencentLoginAvailability();
        self.adjustContentToAccommodateKeyboard = AdjustContentToAccommodateKeyboard(target: self);
    }
    
    func checkTencentLoginAvailability(){
        var tencentLoginEnabled = false;
        var connectionToNetwork = self.networkCheck();
        if(connectionToNetwork){
            var url = "/api/v1/thirdpartyloginavailability";
            var localTencentLoginEnabled: AnyObject? = Utils.getValue("tencentLoginEnabled");
            if(localTencentLoginEnabled == nil || !(localTencentLoginEnabled as Bool)){
                var data: AnyObject? = HttpUtils.sendSynchronousRequest(url, method: RequestMethod.GET, requestBody: nil);
                if(data != nil){
                    var thirdPartyLogin = data as NSDictionary;
                    tencentLoginEnabled = thirdPartyLogin.objectForKey("tencentLoginEnabled") as Bool;
                }
            } else {
                tencentLoginEnabled = (localTencentLoginEnabled as Bool);
            }
        }
        Utils.saveData(tencentLoginEnabled, key: "tencentLoginEnabled");
        Utils.debug("Tencent login enabled [\(tencentLoginEnabled)]");
        self.tencentLoginButtion.hidden = !tencentLoginEnabled;
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated);
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning();
        Utils.debug("Memory warning")
    }
    
    @IBAction func accountLogin(sender: UIButton) {
        var connectionToNetwork = self.networkCheck();
        if(connectionToNetwork){
            if(self.usernameTextField.hidden){
                var tencentLoginEnabled = Utils.getValue("tencentLoginEnabled") as Bool;
                if(tencentLoginEnabled){
                    self.tencentLoginButtion.hidden = true;
                }
                self.accountLoginButton.hidden = true;
                
                self.usernameTextField.hidden = false;
                self.passwordTextField.hidden = false;
                self.loginButton.hidden = false;
                self.hideInputBoxButton.hidden = false;
            }
        }
    }
    
    @IBAction func accountLoginAuthorisations(sender: UIButton) {
        self.authorisations();
    }
    
    @IBAction func hideAccountLoginView(sender: UIButton) {
        self.usernameTextField.hidden = true;
        self.passwordTextField.hidden = true;
        self.loginButton.hidden = true;
        self.hideInputBoxButton.hidden = true;
        
        self.accountLoginButton.hidden = false;
        var tencentLoginEnabled = Utils.getValue("tencentLoginEnabled") as Bool;
        if(tencentLoginEnabled){
            self.tencentLoginButtion.hidden = false;
        }
        
    }
    
    //Register account
    @IBAction func registerAccount(sender: UIButton) {
        var storyboard = UIStoryboard(name: "Login", bundle: nil);
        var registerViewController = storyboard.instantiateViewControllerWithIdentifier("registerView") as RegisterViewController;
        self.presentViewController(registerViewController, animated: true, completion: nil);
    }
    
    func authorisations(){
        var username = self.usernameTextField.text;
        var password = self.passwordTextField.text;
        
        var url = "/api/v1/authorisations";
  
        var encodedUsernamePassword = Utils.encodeUsernamePassword(username, password: password);
        
        var authorization = RequestHeader(field: "Authorization", value: encodedUsernamePassword);
        
        var data: AnyObject? = HttpUtils.sendSynchronousRequest(url, method: RequestMethod.POST, requestBody: nil, headers: authorization);
        
        if(data != nil){
            self.loginSuccess(data!);
        }
    }
    
    func loginSuccess(data:AnyObject){
        var dictionary = data as NSDictionary;
        
        var guid = dictionary.objectForKey("guid") as String;
        
        var token = dictionary.objectForKey("token") as String;
        
        Utils.saveData(guid, key: "guid");
        
        Utils.saveData(token, key: "token");
        
        let setup = dictionary.objectForKey("setup") as Bool;
        
        AuthorisationService.registerDevice()
        
        self.toggleView(setup);
    }
    
    func toggleView(setup:Bool){
        var viewController:UIViewController!;
        if(setup){
            viewController = AuthorisationService.mainView();
        } else {
            var storyboard:UIStoryboard = UIStoryboard(name: "UserInfo", bundle: nil);
            var userInforViewController = storyboard.instantiateViewControllerWithIdentifier("userInfoView") as UserInforViewController;
            userInforViewController.setUserInfo(userInfo);
            viewController = userInforViewController;
        }
        self.presentViewController(viewController, animated: true, completion: nil);
    }
    
    @IBAction func qqLogin(sender: UIButton) {
        var connectionToNetwork = self.networkCheck();
        if(connectionToNetwork){
            self.tencentOAuth.authorize(permissions);
        }
    }
   
    /**
    * 登录成功后的回调
    */
    func tencentDidLogin(){
        self.processing();
        self.tencentOAuth.getUserInfo();
    }
    
    /**
    * 登录失败后的回调
    * \param cancelled 代表用户是否主动退出登录
    */
    func tencentDidNotLogin(cancelled: Bool){
        
    }
    
    /**
    * 登录时网络有问题的回调
    */
    func tencentDidNotNetWork(){
        
    }
    
    func getUserInfoResponse(response: APIResponse!) {
        if(response != nil && response.retCode == 0){
            var openId = self.tencentOAuth.openId;
            var accessToken = self.tencentOAuth.accessToken;
            var userInfoDictionary = response.jsonResponse as NSDictionary;
            var avatarURL = userInfoDictionary.objectForKey("figureurl_qq_2") as String;
            var nickname = userInfoDictionary.objectForKey("nickname") as String;
            var genderFromTencent = userInfoDictionary.objectForKey("gender") as String;
            var gender = resolveGender(genderFromTencent);
            
            self.userInfo = UserInfo(openId: openId, accessToken: accessToken, nickname: nickname, gender: gender, avatarURL: avatarURL);
            
            var url = "/api/v1/user/thirdpartylogin";
            var createUser = NSMutableDictionary();
            createUser.setObject(openId, forKey: "openId");
            createUser.setObject(accessToken, forKey: "accessToken");
            
            
            var data: AnyObject? = HttpUtils.sendSynchronousRequest(url, method: RequestMethod.POST, requestBody: createUser);
            if(data != nil){
                self.processComplete();
                
                self.loginSuccess(data!);
            }
        }
        
    }
    
    func resolveGender(gender:String) -> String{
        return gender == "男" ? "MALE" : "FEMALE";
    }
    
    func networkCheck() -> Bool{
        var reachability = Reachability.reachabilityForInternetConnection();
        var status = reachability.currentReachabilityStatus();
        if(self.notReachableView == nil && status.value == NotReachable.value){
            var margin:CGFloat = 10;
            var height:CGFloat = 45;
            var width = self.view.frame.width - margin * 2;
            var frame = CGRect(x: margin, y: -height, width: width, height: height);
            var view = UIView(frame: frame);
            view.alpha = 0.75;
            view.backgroundColor = UIColor.blackColor();
            view.layer.masksToBounds = true;
            view.layer.cornerRadius = height * 0.15;
            
            var labelFrame = CGRect(x: 0, y: 0, width: width, height: height);
            var label = UILabel(frame: labelFrame);
            label.text = "世界上最遥远的距离就是没网络.请检查网络";
            label.font = Utils.fontHupo(14);
            label.textColor = UIColor.whiteColor();
            label.textAlignment = NSTextAlignment.Center;
            view.addSubview(label);
            self.view.addSubview(view);
            self.notReachableView = view;
            
            UIView.animateWithDuration(0.3, animations: { () -> Void in
                view.frame.origin.y = 0;
            });
            NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: Selector("hideNotReachableView:"), userInfo: nil, repeats: false);
        }
        return (status.value != NotReachable.value);
    }
    
    func hideNotReachableView(timer:NSTimer){
        UIView.animateWithDuration(0.3, animations: { () -> Void in
            self.notReachableView!.frame.origin.y = -self.notReachableView!.frame.height;
            }, completion: { (complete:Bool) -> Void in
                self.notReachableView!.removeFromSuperview();
                self.notReachableView = nil;
        });
    }
}
